{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/examples/memory/Mem0Memory.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Mem0\n",
    "\n",
    "Mem0 (pronounced “mem-zero”) enhances AI assistants and agents with an intelligent memory layer, enabling personalized AI interactions. It remembers user preferences and traits and continuously updates over time, making it ideal for applications like customer support chatbots and AI assistants.\n",
    "\n",
    "Mem0 offers two powerful ways to leverage our technology: our [managed platform](https://docs.mem0.ai/platform/overview) and our [open source solution](https://docs.mem0.ai/open-source/quickstart)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you're opening this Notebook on colab, you will probably need to install LlamaIndex 🦙."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-index llama-index-memory-mem0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Setup with Mem0 Platform\n",
    "\n",
    "Set your Mem0 Platform API key as an environment variable. You can replace `<your-mem0-api-key>` with your actual API key:\n",
    "\n",
    "> Note: You can obtain your Mem0 Platform API key from the [Mem0 Platform](https://app.mem0.ai/login).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"MEM0_API_KEY\"] = \"m0-...\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using `from_client` (for Mem0 platform API): "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.memory.mem0 import Mem0Memory\n",
    "\n",
    "context = {\"user_id\": \"test_users_1\"}\n",
    "memory_from_client = Mem0Memory.from_client(\n",
    "    context=context,\n",
    "    api_key=\"m0-...\",\n",
    "    search_msg_limit=4,  # Default is 5\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Mem0 Context is used to identify the user, agent or the conversation in the Mem0. It is required to be passed in the at least one of the fields in the `Mem0Memory` constructor.\n",
    "\n",
    "`search_msg_limit` is optional, default is 5. It is the number of messages from the chat history to be used for memory retrieval from Mem0. More number of messages will result in more context being used for retrieval but will also increase the retrieval time and might result in some unwanted results."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using `from_config` (for Mem0 OSS)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ[\"OPENAI_API_KEY\"] = \"<your-api-key>\"\n",
    "config = {\n",
    "    \"vector_store\": {\n",
    "        \"provider\": \"qdrant\",\n",
    "        \"config\": {\n",
    "            \"collection_name\": \"test_9\",\n",
    "            \"host\": \"localhost\",\n",
    "            \"port\": 6333,\n",
    "            \"embedding_model_dims\": 1536,  # Change this according to your local model's dimensions\n",
    "        },\n",
    "    },\n",
    "    \"llm\": {\n",
    "        \"provider\": \"openai\",\n",
    "        \"config\": {\n",
    "            \"model\": \"gpt-4o\",\n",
    "            \"temperature\": 0.2,\n",
    "            \"max_tokens\": 1500,\n",
    "        },\n",
    "    },\n",
    "    \"embedder\": {\n",
    "        \"provider\": \"openai\",\n",
    "        \"config\": {\"model\": \"text-embedding-3-small\"},\n",
    "    },\n",
    "    \"version\": \"v1.1\",\n",
    "}\n",
    "memory_from_config = Mem0Memory.from_config(\n",
    "    context=context,\n",
    "    config=config,\n",
    "    search_msg_limit=4,  # Default is 5\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initialize LLM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.llms.openai import OpenAI\n",
    "\n",
    "llm = OpenAI(model=\"gpt-4o\", api_key=\"sk-...\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mem0 for Function Calling Agents\n",
    "\n",
    "Use `Mem0` as memory for `FunctionAgent`s. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initialize Tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def call_fn(name: str):\n",
    "    \"\"\"Call the provided name.\n",
    "    Args:\n",
    "        name: str (Name of the person)\n",
    "    \"\"\"\n",
    "    print(f\"Calling... {name}\")\n",
    "\n",
    "\n",
    "def email_fn(name: str):\n",
    "    \"\"\"Email the provided name.\n",
    "    Args:\n",
    "        name: str (Name of the person)\n",
    "    \"\"\"\n",
    "    print(f\"Emailing... {name}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.agent.workflow import FunctionAgent\n",
    "\n",
    "agent = FunctionAgent(\n",
    "    tools=[email_fn, call_fn],\n",
    "    llm=llm,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/loganmarkewich/Library/Caches/pypoetry/virtualenvs/llama-index-caVs7DDe-py3.10/lib/python3.10/site-packages/mem0/client/main.py:33: DeprecationWarning: output_format='v1.0' is deprecated therefore setting it to 'v1.1' by default.Check out the docs for more information: https://docs.mem0.ai/platform/quickstart#4-1-create-memories\n",
      "  return func(*args, **kwargs)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello Mayank! How can I assist you today?\n"
     ]
    }
   ],
   "source": [
    "response = await agent.run(\"Hi, My name is Mayank.\", memory=memory_from_client)\n",
    "print(str(response))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Got it, Mayank! Your preferred way of communication is Email. If there's anything specific you need, feel free to let me know!\n"
     ]
    }
   ],
   "source": [
    "response = await agent.run(\n",
    "    \"My preferred way of communication would be Email.\",\n",
    "    memory=memory_from_client,\n",
    ")\n",
    "print(str(response))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Emailing... Mayank\n",
      "Emailing... Mayank\n",
      "Calling... Mayank\n",
      "Emailing... Mayank\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I've sent you an update on our product via email. If you have any other questions or need further assistance, feel free to ask!\n"
     ]
    }
   ],
   "source": [
    "response = await agent.run(\n",
    "    \"Send me an update of your product.\", memory=memory_from_client\n",
    ")\n",
    "print(str(response))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mem0 for ReAct Agents\n",
    "\n",
    "Use `Mem0` as memory for `ReActAgent`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.agent.workflow import ReActAgent\n",
    "\n",
    "agent = ReActAgent(\n",
    "    tools=[call_fn, email_fn],\n",
    "    llm=llm,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = await agent.run(\"Hi, My name is Mayank.\", memory=memory_from_client)\n",
    "print(str(response))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = await agent.run(\n",
    "    \"My preferred way of communication would be Email.\",\n",
    "    memory=memory_from_client,\n",
    ")\n",
    "print(str(response))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = await agent.run(\n",
    "    \"Send me an update of your product.\", memory=memory_from_client\n",
    ")\n",
    "print(str(response))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = await agent.run(\n",
    "    \"First call me and then communicate me requirements.\",\n",
    "    memory=memory_from_client,\n",
    ")\n",
    "print(str(response))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llama-index-caVs7DDe-py3.10",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
